const getWeChatAccessToken = require('./getWechatAccessToken')
const https = require('https')
const fs = require('fs')


function getWeChatUrlScheme() {
    return new Promise(async (reslove, reject) => {

        fs.readFile('./url.txt', async (err, res) => {
            if (res && JSON.parse(res).expires_in > Date.now()) {
                console.log('网址未过期')
                reslove(JSON.parse(res))
            } else {
                const data = await getWeChatAccessToken()
                const request = https.request(`https://api.weixin.qq.com/wxa/generatescheme?access_token=${data.access_token}`, {
                    method: "POST",
                    data: {
                        access_token: data.access_token
                    }
                }, (result) => {
                    result.on('data', (d) => {
                        // process.stdout.write(d);
                        const urlObj = JSON.parse(d.toString())
                        urlObj.expires_in = Date.now() + (60 * 60 * 24 * 1000)
                        fs.writeFileSync('./url.txt', JSON.stringify(urlObj))

                        reslove(JSON.parse(d.toString()))
                    });

                })
                request.on('error', (e) => {
                    console.error(e);
                });
                request.end()
            }
        })

    })
}

module.exports = getWeChatUrlScheme